package com.xmc.common;

import com.xmc.pojo.User;
import com.xmc.utils.BaseContext;
import org.apache.http.HttpResponse;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @简单描述：登录过滤器
 * @Author:
 * @Date: 2022  20时32分48秒
 */
@WebFilter(filterName = "userFilter",urlPatterns = "/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

   public boolean checkUri(String uri){
        String[] allowUri = new String[]{
                "/register.jsp"
                ,"static",
                "login"};
       for (int i = 0; i < allowUri.length; i++) {
           if (uri.contains(allowUri[i])){
               System.out.println("放行的资源:"+allowUri[i]);
               return true;
           }
       }
       return false;
   }
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        String uri = request.getRequestURI();
        if (checkUri(uri)){
            chain.doFilter(req, resp);
        }else {
            User currentUser = BaseContext.getCurrentUser(request);
            if (currentUser != null){
                chain.doFilter(req, resp);
            }else {
                request.setAttribute("msg","您尚未登录，请登录");
                response.sendRedirect("/MyStudentMaster_war/login.jsp");
            }
        }
    }

    @Override
    public void destroy() {

    }

}
